<template>
	<view class="send">
		<view class="head">
			<view>个人资料</view>
			<view class="circle-btn">
				<text class="txt" @click="back">返</text>
			</view>
		</view>
     
		<view class="info-form">
			<form @submit="formSubmit">
				<view class="form-item">
					<view class="label-area">
						<label>
							<view class="txt fade-white-font-color">头像</view>
						</label>
					</view>

					<view class="input-area">
						<view class="box">

							<image class="avatar" :src="avatarUrl" mode="aspectFill"></image>
							<text class="edit" @click="showImageSourceSelector"> > </text>
						</view>
					</view>
				</view>


				<view class="form-item">
					<view class="label-area">
						<label>
							<view class="txt fade-white-font-color">姓名</view>
						</label>
					</view>

					<view class="input-area">
						<view class="box">
							<input focus  v-model="formData.nickName" adjust-position="false"
							    placeholder="请输入姓名" class="custom-input"
								placeholder-style="color: rgba(255,255,255, 0.8);"
								/>
							<text class="edit"> > </text>
						</view>
					</view>
				</view>



				<!-- 				<view class="form-item">
					<view class="label-area">
						<label>
							<view class="txt fade-white-font-color">性别</view>
						</label>
					</view>

					<view class="input-area">
						<view class="box">
							<picker :range="sexs.map(v=> v.label)" :value="formData.sex" @change="onSexChange" class="custom-input">
								<view class="picker">
									<text>{{ formData.sex == 1 ? '男' : '女' }}</text>
								</view>
							</picker>

							<text class="edit"> > </text>
						</view>
					</view>
				</view> -->


				<view class="form-item">
					<view class="label-area">
						<label>
							<view class="txt fade-white-font-color">手机号</view>
						</label>
					</view>

					<view class="input-area">
						<view class="box">
							<input v-model="formData.mobile" disabled placeholder="请输入正确手机号" class="custom-input"
								placeholder-style="color: rgba(255,255,255, 0.8);" />
							<!-- <text class="edit"> > </text> -->
						</view>
					</view>
				</view>


			</form>
		</view>

      
		<tabarea>
			<view class="tap-area-slot">
				<text class="title" @click="save">保存</text>
			</view>
		</tabarea>

	</view>
</template>


<script>
	
	import * as api from '../../utils/api.js';
	import { checkPhone } from '../../utils/untils.js';
	import tabarea from '../../components/taparea.vue';
	const imgPrex = 'https://storage.longdiankj.com/prod-api';
	export default {
		components: {
			tabarea
		},
		data() {
			return {
				imgPrex,
				wareHouse: '',
				warehouses: ['苹果仓', '橙子仓', '葡萄仓'],
				eltrInfoOptions: [{
						label: '苹果',
						value: 'apple'
					},
					{
						label: '香蕉',
						value: 'banana'
					},
					{
						label: '橙子',
						value: 'orange'
					}
				],
				selectedIndex: -1, // 给电子信息产品使用的
				sexs: [{
					label: '女',
					val: 0
				}, {
					label: '男',
					val: 1
				}],
				selectedImage: null,
				formData: {
					avatar: '',
					nickName: '',
					mobile: '',
				}
			}
		},
			
		computed: {
			// 兼容微信头像
			avatarUrl () {
				if (!this.formData.avatar) return '/static/default-avatar.jpg';
				if (this.formData.avatar && this.formData.avatar.indexOf('http') > -1) return this.formData.avatar;
				return this.imgPrex + this.formData.avatar;
			}
		},
		onLoad() {
			this.formData.mobile = uni.getStorageSync('userPhone');
			this.getUserInfo();
		},
	
		methods: {
			 onFocus(e) {
			    
			      uni.pageScrollTo({
			        scrollTop: e.detail.height, // 让页面滚动到合适的位置
			        duration: 300
			      });
			   
			  },
			  onBlur() {
			    uni.pageScrollTo({
			      scrollTop: 0, // 失焦后回到顶部
			      duration: 300
			    });
			  },
			async getUserInfo () {
			    const res = await api.getUserInfo();
				this.formData = Object.assign(this.formData, res.appUser) 
			},
			 uploadAvatar (filePath) {
			   const token = uni.getStorageSync('token');
			   uni.uploadFile({
			           url: 'https://storage.longdiankj.com/prod-api/applet/common/avatar', // 后端接收文件上传的接口地址
			           filePath: filePath,
			           name: 'file', // 后端接收文件的字段名
			           header: {
			             'Authorization': `Bearer ${token}` 
			           },
			           
			           success: (res) => {
			   			   const data = JSON.parse(res.data);
			               this.formData.avatar = data.imgUrl;
			           },
			           fail: (err) => {
			             console.log('上传请求失败:', err);
			           }
			         });
			},
			onSexChange(e) {
				this.formData.sex = e.detail.value
			},
			showImageSourceSelector() {
				uni.showActionSheet({
					itemList: ['从微信头像获取', '从相册选择', '拍照'],
					success: (res) => {
						switch (res.tapIndex) {
							case 0:
								// 用户选择从微信头像获取
								this.getAvatarFromWeChat();
								break;
							case 1:
								// 用户选择从相册选择
								this.chooseImageFromAlbum();
								break;
							case 2:
								// 用户选择拍照
								this.takePhoto();
								break;
						}
					},
					fail: (err) => {
						console.log('显示操作菜单失败:', err);
					}
				});
			},
			// 从微信头像获取地址-- 获取的是远程地址url 
			getAvatarFromWeChat() {
				uni.chooseAvatar({
					success: (res) => {
						this.formData.avatar = res.avatarUrl;
						console.log('获取到的微信头像:', res.avatarUrl);
					},
					fail: (err) => {
						console.log('获取微信头像失败:', err);
					}
				});
			},
			chooseImageFromAlbum() {
				
				uni.chooseImage({
					count: 1, // 最多选择 1 张图片
					sourceType: ['album'], // 只从相册选择
					success: (res) => {
						const filePath = res.tempFilePaths[0];
					    this.uploadAvatar(filePath);
					},
					fail: (err) => {
						console.log('从相册选择图片失败:', err);
					}
				});
			},

			takePhoto() {
				uni.chooseImage({
					count: 1, // 最多选择 1 张图片
					sourceType: ['camera'], // 只使用相机拍照
					success: async (res) => {
						const filePath = res.tempFilePaths[0];
						this.uploadAvatar(filePath);
				
					},
					fail: (err) => {
						console.log('拍照失败:', err);
					}
				});
			},
			
			save() {
				const that = this
				uni.showModal({
					title: '提示',
					content: '确定要修改个人信息吗？',
					confirmText: '确定',
					cancelText: '取消',
					success: function(res) {
						if (res.confirm) {
							console.log('用户点击了确定');
							that.formSubmit()
						} else if (res.cancel) {
							console.log('用户点击了取消');
						}
					}
				});
			},
	
	
			back() {
				uni.navigateBack()
			},
			checkForm() {
				let errMsg = '';
				if (this.formData.mobile && checkPhone(this.formData.mobile)) {
					errMsg = '手机号格式不正确'
				}
				if (errMsg) {
					this.myToast(errMsg);
				}

				return !errMsg;
			},
			async formSubmit() {

				const formData = this.formData;
				const pass = this.checkForm();
				if (!pass) return;
				debugger
				const params = {
					avatar: formData.avatar,
					mobile: formData.mobile,
					nickName: formData.nickName,
				}
				const res = await api.updateUserInfo(params);
				this.myToast(res.msg);

			},
			myToast(msg, icon = 'none') {
				uni.showToast({
					icon: icon,
					title: msg,
					duration: 2000
				})
			},
		},
		
	}
</script>

<style lang="scss">
	.send {
		color: white;
		padding: 40rpx 20rpx;
		align-items: center;


		.circle-btn {
			width: 120rpx;
			height: 120rpx;
			border-radius: 50%;
			background-color: #e5b44d;
			text-align: center;
			line-height: 120rpx;

			.txt {
				color: black;
				font-size: 46rpx;
			}
		}

		.sqaure-btn {
			width: 90rpx;
			height: 90rpx;
			border-radius: 8rpx;
			background-color: yellow;
			text-align: center;
			line-height: 90rpx;
			font-size: 40rpx;
			background-color: rgba(0, 0, 0, 1);

			.txt {
				color: white;
			}
		}

		.linear-gradient-back {
			background: linear-gradient(to bottom right, #f2ebce, #856925);
		}

		.linear-gradient-order {
			background: linear-gradient(to bottom right, #ede5c1, #f8ce3d);
		}

		.head {
			display: flex;
			padding: 40rpx 10rpx;
			justify-content: space-between;
			align-items: center;
			font-size: 46rpx;
		}

		.info-form {
			font-size: 30rpx;
			padding: 40rpx 10rpx;
			border-radius: 10rpx;
			background-color: rgba(0, 0, 0, 0.3);

			.form-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin: 30rpx 0;
                font-size: 46rpx;
				.avatar {
					width: 90rpx;
					height: 90rpx;
					border-radius: 10rpx;
					color: white;
				}

				.edit {
					display: inline-block;
					margin-left: 10rpx;
				}

				.label-area {
					.txt {					
						width: 6em;
						display: inline-block;
					}

				}

				.input-area {
					flex: 1;
					margin-right: 1em;

					.box {
						display: flex;
						align-items: center;
						justify-content: flex-end;

						.custom-input {
							height: 42px;
							line-height: 42rpx;
							font-size: 42rpx;
							text-align: right;
						}
					}
				}
			}
		}

		.tap-area {
			margin: 80rpx 16rpx;

			.tap-area-slot {
				.title {
					font-size: 60rpx;
					letter-spacing: 20rpx;
					color: white;
				}
			}
		}


	}
</style>